import { invokeAPi, invokeAsyncAPi } from "@/xz-fn";
import { getLocalStorage, setLocalStorage } from '@/utils/storage';

export interface HOTKEYEVENT {
  keyCode: number,
  key: string, 
  ctrlKey: boolean, 
  shiftKey: boolean, 
  altKey: boolean
}
export interface HOTKEYINFO {
  keyModifierInt: number, 
  keyCode: number,
  keyStr: string,
  id?: number
}

// 设置默认热键
export async function setDefaultHotKey(){
  const funTypes = [
    {
      funType: 0, // 划词翻译
      event: { 
        keyCode: 0,
        key: "",
        shiftKey: false,
        ctrlKey: false,
        altKey: false
      } // 默认不设置
      // event: { 
      //   keyCode: 67,
      //   key: "C",
      //   shiftKey: false,
      //   ctrlKey: true,
      //   altKey: true
      // }
    },
    {
      funType: 1, // 截图翻译
      event: { 
        keyCode: 68,
        key: "D",
        shiftKey: false,
        ctrlKey: true,
        altKey: true
      }
    }
  ];
  const ps = funTypes.map(async ({ funType, event }) => {
    const storageName = 'hotKeyInfo_' + funType;
    let keyInfo = getLocalStorage(storageName);
    if (keyInfo) {
      if(keyInfo.id){
        // 存在热键id代表是启用状态，程序启动时需要重新设置一遍
      }else{
        return
      }
    }else{
      keyInfo = getHotKeyCode(event);
    }
    if(!keyInfo){
      return
    }
    const { keyModifierInt, keyCode } = keyInfo
    const res: {id: number} = await invokeAsyncAPi("fq_RegisterHotKey", funType, keyModifierInt, keyCode);
    if(res?.id) {
      keyInfo.id = res.id as number;
    }
    setLocalStorage(storageName, { ...keyInfo });
  })
  await Promise.all(ps).catch(() => {});
}

// 获取热键按键信息
export function getHotKeyCode(event: HOTKEYEVENT){
  const { keyCode, key: keyStr, ctrlKey, shiftKey, altKey } = event
  if([16, 17, 18, 46, 32].includes(keyCode)){
    return
  }
  const keyModifierInt = getHotKeyModifierInt(event); // 按键修饰符
  if(!keyModifierInt){
    return
  }
  const keyArr = []
  if(ctrlKey){
    keyArr.push("Ctrl");
  }
  if(shiftKey){
    keyArr.push("Shift");
  }
  if(altKey){
    keyArr.push("Alt");
  }
  keyArr.push(keyStr.replace(/^./, (match) => match.toUpperCase()))
  return {
    keyModifierInt,
    keyCode,
    keyStr: keyArr.join(" + ")
  }
}
// 获取热键修饰符
export function getHotKeyModifierInt(event: HOTKEYEVENT) {
  let modifier = 0;
  if (event.ctrlKey) {
    modifier |= 0x0002; // MOD_CONTROL
  }
  if (event.shiftKey) {
    modifier |= 0x0004; // MOD_SHIFT
  }
  if (event.altKey) {
    modifier |= 0x0001; // MOD_ALT
  }
  // if (event.metaKey) {
  //   modifier |= 0x0008; // MOD_WIN (Meta key on Windows is the Windows key)
  // }
  return modifier;
}
// 获取空白热键信息
export function getEmptyKeyInfo(){
  const data: HOTKEYINFO = {
    keyModifierInt: 0, 
    keyCode: 0,
    keyStr: "",
    id: 0
  }
  return data
}